<!-- 分送配置 -->
<template>
  <view>
		<van-popup v-model="showModel" closeable round position="bottom" :style="{ height: '100%' }"
				@click-close-icon="toClose" @click-overlay="toClose">
			<van-row type="flex" justify="center">
				<van-col offset="3" span="8">
					<van-cell value="分送配置" />
				</van-col>
			</van-row>
			<view class="padding-bottom">
				<view>
          <van-cell icon="newspaper-o" title="已分送列表" title-class="text-bold"/>
					<van-row justify="center">
						<van-col span="6">
							<van-cell title="已办环节" title-class="text-bold"></van-cell>
						</van-col>
						<van-col span="6">
							<van-cell title="办理时间" title-class="text-bold"></van-cell>
						</van-col>
						<van-col span="6">
							<van-cell title="当前环节" title-class="text-bold"></van-cell>
						</van-col>
						<van-col span="6">
							<van-cell title="操作" title-class="text-bold"></van-cell>
						</van-col>
					</van-row>
					<van-row justify="center" v-for="item in fsList">
						<template>
							<van-col span="6">
								<van-cell :title="item.fenbanDept"></van-cell>
							</van-col>
							<van-col span="6">
								<van-cell :title="item.banliTime"></van-cell>
							</van-col>
							<van-col span="6">
								<van-cell :title="item.state"></van-cell>
							</van-col>
							<van-col span="6">
								<!-- <van-cell title="恢复" v-if="item.state == 'closed.completed'" @click='recovery(item.subProInstId)'
													title-class="text-blue"></van-cell> -->
								<van-cell title="撤回" @click='withdraw(item.subProInstId)'
													title-class="text-blue"></van-cell>
							</van-col>
						</template>
					</van-row>
				</view>
			</view>
      <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }" />
			<view class="padding-bottom">
        <van-cell icon="send-gift-o" title="待分送选择" title-class="text-bold"/>
				<van-collapse accordion :border="false">
					<van-cell is-link title="呈送领导" v-model="formData.praiseUserNames" @click="showforward('1')" />
					<forward ref="csForward" @closeSheet="closeSheet" @saveSheet="saveSheet" :showForward="showForwardCs" :tagType="1" :forwardData="formData"></forward>

					<van-cell is-link title="主办部门" v-model="formData.directDeptNames" @click="showforward('2')" />
					<forward ref="zbForward" @closeSheet="closeSheet" @saveSheet="saveSheet" :showForward="showForwardZb" :tagType="2" :forwardData="formData"></forward>

					<van-cell is-link title="协办部门" v-model="formData.copyToDeptNames"  @click="showforward('3')"/>
					<forward ref="xbForward" @closeSheet="closeSheet" @saveSheet="saveSheet" :showForward="showForwardXb" :tagType="3" :forwardData="formData"></forward>
				</van-collapse>
			</view>
			<view class="padding-top-lg padding-bottom-lg">
				<van-row type="flex" justify="space-around">
					<van-col span="10">
						<van-button type="info" round plain hairline block @click="toClose">取消</van-button>
					</van-col>
					<van-col span="10">
						<van-button type="info" round block @click="toSave">分送</van-button>
					</van-col>
				</van-row>
			</view>
		</van-popup>
	</view>
</template>

<script>
import forward from 'pages/admin/components/receiveDoc/compo-forward';

export default {
	components: {
		forward,
	},

  props: {
    showSend: {
      type: Boolean,
      default: false
    },
    paramObject: {
      type: Object
    },
		detailObject: {
      type: Object
    },
		nextActivity: {
			type: Array,
			default: () => []
		}
  },

  data() {
		return {
			showModel: false,
			nextActivities: [],  // 下个节点
			swForm: {},    // 公文详情
			proInstId: '', // openwfswneededdata接口获取
			configId: '',  // openwfswneededdata接口获取
			proDirId: '',  // openwfswneededdata接口获取
			actInstId: '', // openwfswneededdata接口获取
			actDefId: '',  // openwfswneededdata接口获取
			workitemId: '',// openwfswneededdata接口获取
			dsResult: [], // 是否局长办公室代收
			dsList: ['1'],
			fsList: [], 		// 已分送单位集合
			showForwardCs: false, // 显示呈送
			showForwardZb: false, // 显示主办
			showForwardXb: false, // 显示协办
			formData: {}, // 提交的数据
			participants: [], // nextActivities中的参数
		};
  },

	watch: {
		showSend(val) {
			this.showModel = val
		},
		paramObject: {
			handler(nval, oval) {
				if (nval != null && JSON.stringify(nval) != "{}") {
					this.proInstId = nval.proInstId
					this.configId = nval.configId
					this.proDirId = nval.proDirId
					this.actInstId = nval.actInstId
					this.actDefId = nval.actDefId
					this.workitemId = nval.workitemId
					// 获取已分送单位
					this.initAlreadyFs(nval.proInstId)
				}
			},
			immediate: true,
			deep: true
		},
		detailObject: {
			handler(nval, oval) {
				if (nval != null && JSON.stringify(nval) != "{}") {
					this.swForm = nval
					this.formData.praiseUserNames = nval.praiseUserNames
					this.formData.praiseUserIds = nval.praiseUserIds
					this.formData.directDeptNames = nval.directDeptNames
					this.formData.directDeptIds = nval.directDeptIds
					this.formData.mainToUserIds = nval.mainToUserIds
					this.formData.copyToDeptNames = nval.copyToDeptNames
					this.formData.copyToDeptIds = nval.copyToDeptIds
					this.formData.copyToUserIds = nval.copyToUserIds
					// 默认将是否局长秘书代收设为0
					this.formData.jzmsDaishou = '0'
					console.log('--------------watch-handler');
				}
			},
			immediate: true,
			deep: true
		},
		nextActivity: {
			handler(nval, oval) {
				this.nextActivities = nval
			},
			immediate: true,
			deep: true
		}
	},

	created() {
		// console.log('-----------------created');
	},

	mounted() {
		// 初始化单位
		this.initDept()
		// console.log('-----------------mounted');
	},

  methods: {
		// 获取已分送单位
		initAlreadyFs(proInstId) {
			this.$http({
				url: this.$http.adornUrl(`/caac/oa/mhjcomponent/countersign/countersignController/listfensonginfo`),
				method: 'get',
				params: this.$http.adornParams({
					'systemKey': this.cache.get('userInfo').systemKey,
					'systemFlag': this.cache.get('userInfo').systemFlag,
					'proInstId': proInstId
				})
			}).then(({data}) => {
				if(data.code==200){
					// 数组
					this.fsList = data.data
					console.log("------已分送单位-fsList: " + JSON.stringify(data.data));
				}
			})
		},

		// 初始化分送单位
		initDept() {
			this.$http({
				url: this.$http.adornUrl(`/caac/oa/authority/sw/getFensongUserInfo`),
				method: 'get',
				params: this.$http.adornParams({
					'systemKey': this.cache.get('userInfo').systemKey,
					'systemFlag': this.cache.get('userInfo').systemFlag
				})
			}).then(({data}) => {
				if(data.code==200){
					this.formData.cxList = data.data.chengsong
					this.formData.zbList = data.data.zhusong
					this.formData.xbList = data.data.xieban
				}
			})
		},

		// 类型 呈送 主办 协办
		showforward(type){
			if(type == "1" ){
				this.showForwardCs = true
			}else if(type == "2"){
				// 主办只能有一个，主办单位不为空时须先撤回才能再次选择
				if(this.detailObject.mainToUserIds != null && this.detailObject.mainToUserIds != ''){
					this.$toast('先把主办单位撤回后才能进行更换！')
				} else {
					this.showForwardZb = true
				}
			}else if(type == "3"){
				this.showForwardXb = true
        this.$refs.xbForward.init()
			}
		},

		// 关闭sheet
		closeSheet(type) {
			if(type == "1" ){
				this.showForwardCs = false
			}else if(type == "2"){
				this.showForwardZb = false
			}else if(type == "3"){
				this.showForwardXb = false
			}
		},

		// 保存sheet
		saveSheet(data) {
			let type = data.type, result = data.result
			if(type == "1" ) {
				this.showForwardCs = false
				let ids = [], names = []
				result.forEach(t => {
					let arr = t.split('_')
					ids.push(arr[0])
					names.push(arr[1])
				})
        this.formData.jzmsDaishou = data.dsResult
				this.formData.praiseUserIds = this.convertData(this.detailObject.praiseUserIds ,ids)
				this.formData.praiseUserNames = this.convertData(this.detailObject.praiseUserNames ,names)
			} else if(type == "2"){
				this.showForwardZb = false
				let arr = result.split('_')
				this.formData.directDeptIds = arr[0]
				this.formData.directDeptNames = arr[1]
				this.formData.mainToUserIds = arr[2]
				// 选中主办后，将该单位从协办中移除
				if(arr[0] != '') {
				  this.removeCopyDeptId(arr[0])
				}
			} else if(type == "3"){
				console.log('---------------result:' + result)
				this.showForwardXb = false
				let ids = [], names = [], userIds = []
				result.forEach(t => {
					let arr = t.split('_')
					ids.push(arr[0])
					names.push(arr[1])
					userIds.push(arr[2])
				})

				this.formData.copyToDeptIds = this.convertData(this.detailObject.copyToDeptIds ,ids)
				this.formData.copyToDeptNames = this.convertData(this.detailObject.copyToDeptNames ,names)
				this.formData.copyToUserIds = this.convertData(this.detailObject.copyToUserIds, userIds)
			}
		},

		convertData(pData, nData) {
			if(pData != null && pData != '') {
				if(nData.length > 0) {
				  let n = nData.filter( (t) => pData.indexOf(t) < 0)
          if(n.length > 0) {
            return pData + ',' + n.toString()
          } else {
					  return pData
          }
				} else {
					return pData
				}
			} else {
				return nData.toString()
			}
		},

		// 协办移除
		removeCopyDeptId(deptId) {
			let copyDeptId = this.formData.copyToDeptIds
			if(copyDeptId == null || copyDeptId == '' || deptId == '') {
				return
			}
			let copyDeptName = this.formData.copyToDeptNames
			let copyUserId = this.formData.copyToUserIds

			let dept = this.formData.xbList.filter( t => t.deptId == deptId)
			dept = dept.length > 0 ? dept[0] : dept
			let cdId = copyDeptId.split(',').filter( t => t != deptId)
			let cdName = copyDeptName.split(',').filter( t => t != dept.deptName)
			let cuId = copyUserId.split(',').filter( t => t != dept.userId)

			this.formData.copyToDeptIds = cdId.toString()
			this.formData.copyToDeptNames = cdName.toString()
			this.formData.copyToUserIds = cuId.toString()
		},

		// 取消按钮
		toClose(){
			this.$emit('closeSend', this.showModel)
		},

		// 分送确认框
		toSave(){
			if(this.validateForm()) {
				this.$dialog.confirm({
				  confirmButtonColor: '#1989fa',
				  title: '系统提示',
				  message: '确认分送吗?',
				}).then(() => {
					// 首先判断已分送集合是否为空
					let isFsNull = this.fsList == null || this.fsList.length == 0
					// 再判断分送集合中是否都是注办送审
					let isZbss = false
					if(!isFsNull) {
						let zbssList = this.fsList.filter( t => t.fenbanDept == '注办送审')
						if(zbssList.length == this.fsList.length) {
							isZbss = true
						}
					}
					if(isFsNull || isZbss) {
						// 分送
						this.saveSend()
					} else {
						// 追加分送
						this.addToSend()
					}
				}).catch(() => {
					// on cancel
				})
			}
		},

		// 校验
		validateForm() {
			// 呈送、主办、协办中至少选一个
			if(this.util.isEmpty(this.formData.praiseUserIds) && this.util.isEmpty(this.formData.mainToUserIds)
					&& this.util.isEmpty(this.formData.copyToUserIds)) {
				this.$toast('呈送、主办、协办中至少选一个')
				return false
			}
			return true
		},

		// 分送
		saveSend(){
			this.updateForm()

			console.log("-----------分送-swForm: " + JSON.stringify(this.swForm));
			console.log("-----------分送-nextActivities: " + JSON.stringify(this.nextActivities));

			this.$httploading({
        url: this.$http.adornUrl(`/caac/wfm/ApplicationController/completeWorkitem`),
				method: 'post',
				params:{
					'systemKey': this.cache.get('userInfo').systemKey,
					'systemFlag': this.cache.get('userInfo').systemFlag,
					data: this.$http.adornData({
						swForm: this.swForm,
						wfmData:{
							'configId': this.configId,
							'proDirId': this.proDirId,
							'actDefId': this.actDefId,
							'proInstId':this.proInstId, // 详情返回的proInstId
							'actInstId': this.actInstId,
							'workitemId':this.workitemId,
							'nextActivities': this.nextActivities
						},
						jzmsDaishou: this.formData.jzmsDaishou
				 })
				}
			}).then(({data}) => {
				console.log("--------------分送-data-->>: " + JSON.stringify(data));
				if(data.code==200){
					if(this.actDefId == 'zbss') {
						this.$httploading({
							url: this.$http.adornUrl(`/caac/oa/authority/sw/dofensong?systemKey=`+this.cache.get('userInfo').systemKey+`&systemFlag=`+this.cache.get('userInfo').systemFlag),
							method: 'post',
							data:JSON.stringify({
								proInstId: this.swForm.proInstId,          // 详情返回的proInstId
								praiseUserIds: this.formData.praiseUserIds,// 选择的领导 多个,分割
								mainToUserIds: this.formData.mainToUserIds,// 选择的主办
								copyToUserIds: this.formData.copyToUserIds,// 选择的协办 多个,分割
								title: this.swForm.title,                  // 详情返回的title
								configId: 'gljzlc',                        // 固定
								rootProInstId: this.proInstId,             // openwfswneededdata返回的proInstId
								jzmsDaishou: this.formData.jzmsDaishou     //是否局长办公室代收 勾了是1 没勾是0
							})
						}).then(({swData}) => {
							console.log("---------分送-zbss-data: " + JSON.stringify(swData));
							if(swData.code==200){
								this.$toast('操作成功')
								uni.redirectTo({
									 url:'/pages/admin/receive/doList'
								})
							}else{
								this.$toast(swData.message+' code:'+swData.code)
							}
						})
					} else {
						this.$toast('操作成功')
						uni.redirectTo({
							 url:'/pages/admin/receive/doList'
						})
					}
				}else{
					this.$toast(data.message+' code:'+data.code)
				}
			})
		},

		// 更新swForm
		updateForm() {
			this.$set(this.swForm, 'praiseUserIds', this.formData.praiseUserIds)
			this.$set(this.swForm, 'praiseUserNames', this.formData.praiseUserNames)
			this.$set(this.swForm, 'mainToUserIds', this.formData.mainToUserIds)
			this.$set(this.swForm, 'directDeptNames', this.formData.directDeptNames)
			this.$set(this.swForm, 'directDeptIds', this.formData.directDeptIds)
			this.$set(this.swForm, 'copyToUserIds', this.formData.copyToUserIds)
			this.$set(this.swForm, 'copyToDeptNames', this.formData.copyToDeptNames)
			this.$set(this.swForm, 'copyToDeptIds', this.formData.copyToDeptIds)

			if(this.formData.praiseUserIds != null && this.formData.praiseUserIds != '') {
				let arr = this.formData.praiseUserIds.split(',')
				arr.forEach( id => {
					this.participants.push('user:' + id)
				})
			} else {
				this.participants.push('user:')
			}
			if(this.nextActivities != null && this.nextActivities.length > 0) {
				this.$set(this.nextActivities[0], 'participants', this.participants.toString())
			}
		},

		// 追加分送
		addToSend() {
			this.updateForm()
			this.$httploading({
				url: this.$httploading.adornUrl(`/caac/oa/authority/sw/updateSw`),
				method: 'post',
				params: this.$httploading.adornParams({
					'systemKey': this.cache.get('userInfo').systemKey,
					'systemFlag': this.cache.get('userInfo').systemFlag,
					data: JSON.stringify(this.swForm)
				})
			}).then(({data}) => {
				if(data.code == 200) {
					this.$httploading({
						url: this.$httploading.adornUrl(`/caac/oa/authority/sw/addSubflowAfterSuspended`),
						method: 'post',
						params: this.$httploading.adornParams({
							'systemKey': this.cache.get('userInfo').systemKey,
							'systemFlag': this.cache.get('userInfo').systemFlag,
							data: JSON.stringify({
								proInstId: this.proInstId,
								actInstId: this.actInstId,
								title: this.swForm.title,
								gongwenId: this.swForm.swId,
								subFlowId: "gljzlc",
								otherInfo: "swFensong",
								resourceIds: this.combineAddToIds(),
								psResoyrceIds: "",
								psfsFalg: "",
								jzmsDaishou: this.formData.jzmsDaishou
							})
						})
					}).then(({data}) => {
						if(data.code == 200) {
							this.$toast('操作成功')
							this.$emit('closeSend', this.showModel)
							this.$emit('refreshBtnGroup',true) // 重新加载数据
						} else{
							this.$toast(data.message+' code:'+data.code)
						}
					})
				} else{
					this.$toast(data.message+' code:'+data.code)
				}
			})
		},

		// 追加分送组合resourceIds
		combineAddToIds() {
			// 呈送领导(多个逗号分割)+/+主办+/+协办(多个逗号分割)
			return this.formData.praiseUserIds + "/" + this.formData.mainToUserIds + "/" + this.formData.copyToUserIds
		},

		// 恢复
		recovery(subProInstId){
			this.$toast('该功能正在开发中')
		},
		// 撤回
		withdraw(subProInstId) {
			this.$dialog.confirm({
			  confirmButtonColor: '#1989fa',
			  title: '系统提示',
			  message: '确认撤回吗?',
			})
			.then(() => {
				this.$httploading({
					url: this.$httploading.adornUrl(`/caac/oa/component/workflow/workflowController/swremoveprocess`),
					method: 'post',
					params: this.$httploading.adornParams({
						'systemKey': this.cache.get('userInfo').systemKey,
						'systemFlag': this.cache.get('userInfo').systemFlag,
						'data': JSON.stringify({
							"removeWorkitemIds": this.workitemId,
							"configId": this.configId,
							"subProInstId": subProInstId,
							"proDirId": this.proDirId,
							"proInstId": this.proInstId,
							"actInstId": this.actInstId
						})
					}),
				}).then(({data}) => {
				  console.log('------撤回-data: ' + JSON.stringify(data))
					if (data.code == 200) {
					  // 撤回后修改公文状态
					  this.updatePsfs(data.data.parentActDefName)
					} else {
					  this.$toast(data.message + ' code:' + data.code)
					}
				})
			})
			.catch(() => {
				// on cancel
			})
		},
		// 修改撤回状态
    withdrawState(parentActDefName) {
      this.$httploading({
        url: this.$http.adornUrl(`/caac/oa/authority/sw/chehuifensongState`),
        method: 'post',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,
          'systemFlag': this.cache.get('userInfo').systemFlag,
          'proInstId': this.proInstId,
          'parentActDefName': parentActDefName
        }),
      }).then(({data}) => {
        if (data.code == 200) {
          this.$toast('撤回成功')
          this.$emit('closeSend', this.showModel)
          this.$emit('refreshBtnGroup',true) // 重新加载数据
        } else {
          this.$toast(data.message + ' code:' + data.code)
        }
      })
    },

    // 更新公文分送
		updatePsfs(parentActDefName) {
      this.$httploading({
        url: this.$http.adornUrl(`/caac/oa/authority/sw/updatepsfs`),
        method: 'get',
        params: this.$http.adornParams({
          'systemKey': this.cache.get('userInfo').systemKey,
          'systemFlag': this.cache.get('userInfo').systemFlag,
          'proInstId': this.proInstId
        }),
      }).then(({data}) => {
        this.withdrawState(parentActDefName)
      })
    },
	},

}
</script>

<style>
	.action{
		width: auto !important;
		max-width: 150rpx !important;
	}

	.van-checkbox--horizontal {
		margin-right: 2px;
	}

	/deep/ .van-grid-item__content {
	    display: -webkit-box;
	    display: -webkit-flex;
	    display: flex;
	    -webkit-box-orient: vertical;
	    -webkit-box-direction: normal;
	    -webkit-flex-direction: column;
	    flex-direction: column;
	    box-sizing: border-box;
	    height: 100%;
	    padding: 10px 8px;
	    background-color: #fff;
	}
</style>
